package org.enwey.icarenew.APPUtils;

import android.content.Context;

import org.enwey.icarenew.Activity.Base.BaseActivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by liangyaotian on 2014-07-15.
 */
public class StringUtil {

    public static final String COMMON_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String COMMON_DATE_FORMAT_PRE = "yyyy-MM-dd";

    public static String getTimeStringFromDate(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    public static String getTimeStringFromLong(long time, String format) {
        return new SimpleDateFormat(format).format(new Date(time));
    }

    public static Date dateFromString(String dateString, String format){
        Date result = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            result = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String randomChar(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String getStringFromFloatKeep2(double value) {
        DecimalFormat df = new DecimalFormat("0.0#");
        return df.format(value);
    }

    public static String getStringFromAssets(Context context, String fileName) {
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(((BaseActivity)context).getResources().getAssets().open(fileName)));
            String line = "";
            String result = "";
            while ((line = br.readLine()) != null) {
                result += line;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String showMessage(String message) {
        return message == null ? "" : message;
    }
}
